package com.tanhua.dubbo.api.mongo.impl;

import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;

    @Override
    public void saveVideo(Video video) {
        video.setVid(idWorker.getNextId("video"));
        mongoTemplate.save(video);
    }

    @Override
    public PageResult queryVideoList(Integer page, Integer pagesize) {
        Query query = new Query();
        long counts = mongoTemplate.count(query, Video.class);
        query.with(Sort.by(Sort.Order.desc("created"))).skip((page - 1) * pagesize).limit(pagesize);
        List<Video> videos = mongoTemplate.find(query, Video.class);
        return new PageResult(page.longValue(), pagesize.longValue(), counts, videos);
    }

    @Override
    public PageResult queryByUid(Integer page, Integer pagesize, Long uid) {
        Query query = new Query(Criteria.where("userId").is(uid));
        long counts = mongoTemplate.count(query, Video.class);
        query.with(Sort.by(Sort.Order.desc("created"))).skip((page - 1) * pagesize).limit(pagesize);
        List<Video> videos = mongoTemplate.find(query, Video.class);
        return new PageResult(page.longValue(), pagesize.longValue(), counts, videos);
    }

}
